import importlib
import time
from pymongo import MongoClient
import aiohttp
import pymongo
from bson import ObjectId
# 设置代理
proxies = {
    'http': 'http://127.0.0.1:15732',
    'https': 'http://127.0.0.1:15732'
}
def change_cookies(key):
    # 加载模块
    module_name = 'cookies_pool'
    module = importlib.import_module(module_name)
    # 修改属性值
    new_value = key
    setattr(module, 'wr_skey', new_value)

    # 将修改后的值写回到原始文件
    source_code = ''
    with open(module.__file__, 'r') as file:
        source_code = file.readlines()

    with open(module.__file__, 'w') as file:
        for line in source_code:
            if line.startswith('wr_skey'):
                file.write(f'wr_skey = {repr(new_value)}\n')
            else:
                file.write(line)
    # 重新加载模块以使修改生效
    importlib.reload(module)

def get_proxy():
    import random
    port = random.randint(24000, 24400)
    '''
    hc2.iinti.cn
    hc1.iinti.cn
    wz1.iinti.cn
    haproxy
    '''
    proxies = {'http': f'http://zheng123:zheng123@wz1.iinti.cn:{port}',
               'https': f'http://zheng123:zheng123@wz1.iinti.cn:{port}'}
    return proxies

def get_long_time():
    return str(int(time.time() * 1000))


def get_time():
    return str(int(time.time()))


def get_kuai_proxy():
    # 隧道域名:端口号
    tunnel = "t563.kdltps.com:15818"
    ## 用户名密码方式
    username = "t17055604523596"
    password = "845dth2u"
    proxies = {"http": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel},
               "https": "http://%(user)s:%(pwd)s@%(proxy)s/" % {"user": username, "pwd": password, "proxy": tunnel}}
    return proxies

def get_kuai_aioproxy():
    # 隧道域名:端口号
    tunnel = "t563.kdltps.com:15818"
    ## 用户名密码方式
    username = "t17055604523596"
    password = "845dth2u"
    proxies = aiohttp.BasicAuth(username, password)
    return proxies
basepath = '/media/chenglei3/77D014CED257D1411/AI_car_picture/huaban/'

def get_proxy():
    import random
    port = random.randint(24000, 24400)
    '''
    hc2.iinti.cn
    hc1.iinti.cn
    wz1.iinti.cn
    haproxy
    '''
    proxies = {'http': f'http://zheng123:zheng123@wz1.iinti.cn:{port}',
               'https': f'http://zheng123:zheng123@wz1.iinti.cn:{port}'}
    return proxies

def get_proxy_aio():
    import random
    port = random.randint(24000, 24400)
    proxyUser = "zheng123"
    proxyPass = "zheng123"
    proxyHost = "wz1.iinti.cn"
    proxyPort = 24000

    proxies = aiohttp.BasicAuth(proxyUser, proxyPass)
    return proxies


class mongo_manager():

    def __init__(self, collect_name, client="mongodb://172.23.130.173:27017/", db="tidy"):
        self.client = pymongo.MongoClient(client)
        self.db = self.client[db]
        self.collect = self.db[collect_name]

    def getCollect(self, collect_name: str) -> pymongo.collection.Collection:
        """
        创建集合
        :return:
        """
        if bool(collect_name):
            return self.db[collect_name]
        return self.collect

    def findById(self, id: str):
        myquery = {"_id": ObjectId(id)}
        return self.collect.find_one(myquery)

    def findAll(self, data=None):
        if bool(data):
            return self.collect.find(data)
        return self.collect.find()

    def findOne(self, data=None):
        if bool(data):
            return self.collect.find_one(data)
        return self.collect.find_one()

    def find_one_and_update(self, filter, update_data):
        # pymongo.ReturnDocument.AFTER 表示 返回修改后的文档
        result = self.collect.find_one_and_update(filter=filter, update={'$set': update_data},
                                                  # sort=[("articles_count", -1)],
                                                  return_document=pymongo.ReturnDocument.AFTER)
        return result

    def insertOne(self, data: dict):
        return self.collect.insert_one(data)

    def insertMany(self, datas: list):
        res=self.collect.insert_many(datas)
        return res.inserted_ids

    def updateOne(self, query, new_value):
        newvalues = {"$set": new_value}
        return self.collect.update_one(query, newvalues)
    def pushOne(self, query, new_value):
        newvalues = {"$push": new_value}
        return self.collect.update_one(query, newvalues)
    def updateMany(self, query, new_value):
        newvalues = {"$set": new_value}
        return self.collect.update_many(query, newvalues)

    def updateMany_unset(self, query, new_value):
        newvalues = {"$unset": new_value}
        return self.collect.update_many(query, newvalues)
    # def deleteById(self,id):
    #     return self.collect.remove({"_id", ObjectId(id)})

    def deleteOne(self, myquery):
        return self.collect.delete_one(myquery)

    def deleteMany(self, myquery):
        return self.collect.delete_many(myquery)

    def close(self):
        self.client.close()

    def not_exist(self, query):
        if bool(query):
            data = self.collect.find_one(query)
            if data:
                return False
            return True

    def delete_repeat(self, name):
        pipeline = [
            {
                '$group': {
                    '_id': '${}'.format(name),
                    'count': {'$sum': 1},
                    'duplicates': {'$addToSet': '$_id'}
                }
            },
            {
                '$match': {
                    'count': {'$gt': 1}
                }
            }
        ]

        duplicate_documents = self.collect.aggregate(pipeline)

        for document in duplicate_documents:
            for duplicate_id in document['duplicates'][1:]:
                self.collect.delete_one({'_id': duplicate_id})

        return True

    def add_status_field(self):
        self.collect.update_many({}, {'$set': {'status': '0'}})


